package p0;

/**
 * @author pengjz <br>
 * @version 1.0 <br>
 * @name Leetcode_27 <br>
 * @date 2020/9/11 0:10 <br>
 */
public class Leetcode_28 {
    public int strStr(String haystack, String needle) {
        if (needle.length() > haystack.length()) {
            return -1;
        }
        if (needle.length() == 0) {
            return 0;
        }
        char first = needle.charAt(0);
        int max = haystack.length() - needle.length();
        for (int i = 0; i <= max; i++) {
            if (first != haystack.charAt(i)) {
                while (++i <= max && haystack.charAt(i) != first) ;
            }
            if (i <= max) {
                int j = i + 1;
                int end = j + needle.length() - 1;
                for (int k = 1; j < end && haystack.charAt(j)
                        == needle.charAt(k); j++, k++) ;
                if (j == end) return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        Leetcode_28 l = new Leetcode_28();
        System.out.println(l.strStr("mississippi", "issipi"));
    }
}
